<template>
  <el-table
    ref="tableListRef"
    :data="tableData"
    style="width: 100%"
    height="250"
    highlight-current-row
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="name" label="服务/商品" />
    <el-table-column prop="realPrice" label="售价" align="center" />
    <el-table-column prop="basePrice" label="原价" align="center" />
    <el-table-column prop="description" label="描述" align="center" />
  </el-table>
  <div class="price">
    <div class="num">
      赠送剩余数量:<span class="money">{{ feeNum }}</span>
    </div>
    <div>
      客单费:<span class="money">{{ price }}</span>
    </div>
    <!-- <div class="totalSize">
      免费客单数量:
      <div>￥{{ totalPrice }}</div>
    </div>
    <div class="totalSize">
      客单费:
      <div>￥{{ totalPrice }}</div>
    </div> -->
  </div>
  <div class="btnNext form-footer-btn">
    <div class="left_txt">
      <div>
        钱包余额:<span style="color: red; font-size: 18px; margin-left: 5px">{{
          storeBalance
        }}</span>
      </div>
      <div class="recharge" @click="saveRechargeBtn">充值</div>
    </div>
    <div>
      <el-button
        @click="upChange"
        style="
          border: 1px solid rgb(22, 93, 255);
          color: rgb(22, 93, 255);
          width: 88px;
          height: 32px;
        "
        >上一步</el-button
      >
      <el-button
        type="primary"
        @click="sureChange"
        color="#165dff"
        style="width: 88px; height: 32px"
        >确认</el-button
      >
    </div>
  </div>
  <!-- 扫码支付 -->
  <el-dialog
    :model-value="dialogVisible"
    title="扫码支付"
    @close="closeDialog"
    :close-on-click-modal="false"
    center
    width="50%"
  >
    <div>
      <!-- 前端生成二维码 -->
      <QrcodeGenerator
        :text="codeUrl ?? ''"
        :size="200"
        level="H"
        style="z-index: 99"
        class="code-box"
        v-if="codeUrl"
      />
      <!-- 显示二维码和倒计时 -->
      <div class="error-box">
        <!-- 当二维码显示且倒计时在进行时，显示倒计时 -->
        <div v-if="!showRefresh">
          请在 <span>{{ minutes }}</span> 分
          <span>{{ seconds }}</span> 秒内完成支付
        </div>
        <!-- 当二维码失效或倒计时结束时，显示“刷新”按钮 -->
        <div v-else>
          二维码已失效，请
          <span class="refresh" @click="getCode">刷新</span> 重新支付
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
const emits = defineEmits(['upChange', 'childClick']);
import { nextTick, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import {
  servicesList,
  creatWeChatOrder,
  payVerificationApi,
} from '@/api/service/service.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import QrcodeGenerator from '@/components/QrcodeGenerator/index.vue';
const storeBalance = ref('');
const router = useRouter();
const feeNum = ref('');
const kd = ref('');
import withdraw from '@/modules';
const { accountBalanceApi, freeNumAPI, kdConfigAPI } = withdraw;
// 格式转换
const formatCurrency = (num) => {
  const cleanedNum = Number(num.toString().replace(/,/g, ''));
  return new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(cleanedNum);
};
const props = defineProps({
  payType: {
    type: Number,
    default: 1,
  },
  phone: {
    type: String,
    default: '',
    required: false,
  },
});

const tableData = ref([]);
const codeUrl = ref(null);
const tableListRef = ref(null);
const dialogVisible = ref(false);
const showRefresh = ref(false);
const timeLeft = ref(0);
const moneyLength = ref('');
// 定时器变量
let countdownInterval = null;
let checkPaymentInterval = null;
// 倒计时分和秒的计算
const minutes = computed(() => Math.floor(timeLeft.value / 60));
const seconds = computed(() => timeLeft.value % 60);
//计算客单费
const price = computed(() => {
  return Number(moneyLength.value - feeNum.value) <= 0
    ? '0.0'
    : Number(moneyLength.value - feeNum.value) * kd.value;
});
getServicesList();
// 获取专家服务列表
function getServicesList() {
  servicesList({}).then((res) => {
    tableData.value = res.data;
    if (res.data.length) {
      nextTick(() => {
        tableListRef.value.toggleRowSelection(res.data[0], true);
      });
    }
  });
}
const selectedItems = ref([]);
const handleSelectionChange = (selected) => {
  moneyLength.value = selected.length;
  selectedItems.value = selected;
};
// 计算勾选项的总价并保留两位小数
const totalPrice = computed(() => {
  const sum = selectedItems.value.reduce((total, item) => {
    return total + Number(item.realPrice);
  }, 0);

  return Math.round(sum * 100) / 100; // 返回数值类型，并保留两位小数
});

function upChange() {
  emits('upChange', 3, 2);
}
const getCode = async () => {
  try {
    showRefresh.value = false;
    const row = tableListRef.value.getSelectionRows();
    const data = await creatWeChatOrder({
      fee: totalPrice.value,
      serviceId: row[0].id,
      serviceName: row[0].name,
      studentMobile: props.phone,
    });
    dialogVisible.value = true;
    codeUrl.value = data.data.code_url;
    startCountdownAndCheckPayment({ out_trade_no: data.data.out_trade_no }); // 开始倒计时和支付状态检查
  } catch (error) {
    console.log('error:', error);
  }
};
function sureChange() {
  if (props.payType == 1) return getCode();
  if (selectedItems.value.length) {
    ElMessageBox.confirm('创建会扣除客单费，确定创建吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      emits('upChange', 3, 0, selectedItems.value[0]);
    });
  } else {
    ElMessage({
      type: 'warning',
      message: '请至少选择一个服务!',
    });
  }
}

// 开始倒计时并轮询支付状态
const startCountdownAndCheckPayment = (out_trade_no) => {
  timeLeft.value = 5 * 60; // 5分钟倒计时

  // 清除现有的倒计时和支付状态检查
  if (countdownInterval !== null) clearInterval(countdownInterval);
  if (checkPaymentInterval !== null) clearInterval(checkPaymentInterval);

  // 开始新的倒计时
  countdownInterval = window.setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      if (countdownInterval !== null) clearInterval(countdownInterval); // 倒计时结束
      ElMessage.error('二维码已失效');
      showRefresh.value = true; // 隐藏二维码
      refreshQRCode(); // 倒计时结束时刷新二维码
    }
  }, 1000);

  // 开始轮询支付状态
  checkPaymentInterval = window.setInterval(async () => {
    const { code } = await payVerificationApi(out_trade_no);
    if (code === 20000) {
      if (countdownInterval !== null) clearInterval(countdownInterval); // 停止倒计时
      if (checkPaymentInterval !== null) clearInterval(checkPaymentInterval); // 停止支付检查
      ElMessage.success('支付成功');
      dialogVisible.value = false;
      location.reload(true);
    }
  }, 3000); // 每3秒轮询支付状态
};
// 刷新二维码
const refreshQRCode = async () => {
  if (countdownInterval !== null) clearInterval(countdownInterval); // 清除之前的倒计时
  if (checkPaymentInterval !== null) clearInterval(checkPaymentInterval); // 清除之前的支付状态轮询
  // await addfee(); // 调用addfee重新生成二维码并重新开始倒计时和轮询
};

// 关闭对话框并通知父组件
const closeDialog = () => {
  dialogVisible.value = false;
};
//账户余额
const getUserMoney = async () => {
  try {
    const { data } = await accountBalanceApi();
    storeBalance.value = formatCurrency(data.storeBalance);
  } catch (error) {
    console.log('error:', error);
  }
};
const saveRechargeBtn = () => {
  router.push({ path: '/financialMan/rechargeManage' });
};
//获取渠道配置
const kdList = () => {
  kdConfigAPI({ type: 'kd' }).then((res) => {
    kd.value = res.data.kdPrice;
  });
};
const feeNumBer = async () => {
  const { data } = await freeNumAPI();
  feeNum.value = data;
};

onMounted(() => {
  getUserMoney();
  feeNumBer();
  kdList();
});
</script>

<style lang="scss" scoped>
@import '@/assets/styles/global.scss';
.price {
  display: flex;
  justify-content: right;

  .num {
    margin-right: 20px;
  }
  .money {
    color: red;
    display: inline-block;
    margin-left: 10px;
    font-size: 18px;
  }
}
.btnNext {
  display: flex;
  justify-content: space-between;
  text-align: right;
  margin-top: 10px;
  border-top: 1px solid #e5e6eb;
  padding-left: 24px;
  padding-right: 24px;
  padding-top: 16px;
  .left_txt {
    display: flex;
    align-items: center;
    .recharge {
      margin-left: 10px;
      color: #165dff;
      cursor: pointer;
    }
  }
}

.error-box {
  text-align: center;

  .refresh {
    cursor: pointer;
    color: blueviolet;
  }
}
:deep(.el-table__inner-wrapper) {
  &::before {
    background: none !important;
  }
}
</style>
